home *** CD-ROM | disk | FTP | other *** search
/ CD Actual 80 / CD Actual 80 Julio-Agosto 2003.iso / Linux / LinuxGazette / lg / issue39 / rogers_example05d.c < prev    next >
Encoding:
C/C++ Source or Header  |  2002-08-14  |  1.6 KB  |  87 lines

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. /*
  5.  
  6.     This program is written to demonstrate the <stdlib.h> library.
  7.  
  8.     This program will demonstrate memory allocation using malloc.
  9.  
  10.     Written by James M. Rogers
  11.  
  12.     21 March 1999
  13.  
  14.     Released to the Public Domain on this date.
  15.  
  16. */
  17.  
  18. struct element{
  19.     struct element *next;
  20.     int value;
  21. }element_size;
  22.  
  23. struct element *initialize () {
  24.     struct element *add;
  25.     if(add=(struct element *)malloc(sizeof(element_size))){
  26.         add->next = (struct element *)NULL;
  27.         return add;
  28.     } else {
  29.     return (struct element *)NULL;
  30.     }
  31. }
  32.  
  33. struct element *push (struct element *top, int value) {
  34.  
  35.     struct element *add;
  36.  
  37.     if (add=(struct element *)malloc(sizeof(element_size))){
  38.  
  39.         add->next=top;
  40.         add->value=value;
  41.         top=add;
  42.         return top;
  43.     } else {
  44.     printf("Failed to push a value onto the stack, I am quiting.\n");
  45.     exit (1);
  46.     }
  47. }
  48.  
  49. struct element *pop (struct element *top, int *value) {
  50.  
  51.     struct element *remove;
  52.  
  53.     fflush(stdout);
  54.  
  55.     *value=top->value;
  56.     remove=top;
  57.     top=top->next;
  58.     free(remove);
  59.     
  60.     return top;
  61. }
  62.  
  63. main(){
  64.  
  65.     struct element *stack;
  66.     int x;
  67.  
  68.     if ( !(stack = initialize())){
  69.     printf("Failed to initialize the stack, I am quiting.\n");
  70.     exit (1);
  71.     }
  72.  
  73.     stack = push(stack, 1);
  74.     stack = push(stack, 2);
  75.     stack = push(stack, 4);
  76.     stack = push(stack, 8);
  77.     stack = push(stack, 16);
  78.     stack = push(stack, 32);
  79.     stack = push(stack, 64);
  80.     stack = push(stack, 128);
  81.     stack = push(stack, 256);
  82.  
  83.     while (stack = pop(stack, &x)){
  84.         printf("Return value is \t%d\n", x);
  85.     }
  86. }
  87.